<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>手把手区块链</title>
  <style>
    * {
      font-family: 微软雅黑;
      font-size: 14px;
    }

    h1 {
      text-align: center;
    }

    div, fieldset {
      width: 1272px;
      padding: 5px;
      margin: 5px auto;
      border: 1px solid #0094ff;
    }

    #tbData {
      border: 1px solid #0094ff;
      border-collapse: collapse;
      width: 1280px;
      margin: 0px auto;
    }

    #tbData th {
      color: #fff;
      background-color: #0094ff;
      font-size: 16px;
    }

    #tbData th,
    td {
      border: 1px solid #000;
      text-align: center;
      word-break: break-all;
      padding:3px;
    }

    #divMsg{
      width: 1260px;
      border: 1px solid #000;
      background-color: red;
      padding: 10px;
    }
    #divMsg span{
      color:#fff;
      font-size: 18px;
      font-weight: bolder;
    }

    #content{
      display: inline-block;
      left: 3px;
    }

    #close{
      display: inline-block;
      margin-left: 10px;
      border-bottom: 2px solid #fff;
      cursor: pointer;
    }

    #divNodeOpe span{
      margin: 2px 5px;
      border: 1px dashed #0094ff;
      padding: 1px 3px;
    }
  </style>
  <script src="../js/jquery-3.3.1.min.js"></script>
  <script src="../js/NoteBook.js"></script>
  <script>
    // -------------------------- 一、工具方法----------------------------
    function gel(id) {
      return document.getElementById(id);
    }

    //0.1 时间戳转换
    function timestampToTime(timestamp) {
        var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = date.getDate() + '<br/>';
        h = date.getHours() + ':';
        m = date.getMinutes() + ':';
        s = date.getSeconds();
        return Y+M+D+h+m+s;
    }

    //客户端网络数据 和 业务dom操作
    var noteBook = new NoteBook();

    //0.2 生成url
    function makeUrl(relativePath){
      return '/'+relativePath;
    }
    
    //0.3 消息显示
    function showMsg(msg) {
       var $divMsg = $('#divMsg');
       $('#content',$divMsg).html(msg);
       $divMsg.show();
    }

    //0.4 消息关闭
    function closeMsg() {
       $('#divMsg').hide();
    }

    // -------------------------- 二、账本业务处理----------------------------
    //1.0 加载数据 
    function loadFromServer(func) {
      try {
        $.getJSON(makeUrl('getNoteBookData'),function(data,statue,xhr){
          noteBook.initData(data);
          func(noteBook);
        })
      } catch (error) {
        console.log(error);
      }
    }

    //2.0 添加创世区块的时候,要保证日记本是空的
    function addGenesis() {
      if (!noteBook.isEmpty()) {
        alert("添加创世区块的时候,必须保证日记本是空的");
      }else{
        var strCon = 'blockContent='+$('#txtContent').val();
        $.post(makeUrl('addGenesis'),strCon,function(data,status){
          if(data.state==1){
            noteBook.addNote(data.content);
            loadTable();
            $('#txtContent').val('');
          }else{
            alert(data.content);
          }
        },'json');
      }
    }

    //3.0 添加普通区块,必须有创世区块,普通区块只能添加在创世区块之后 
    function addNote(note) {
      if (noteBook.isEmpty()) {
        alert("添加普通区块之前必须有创世区块");
      }else{
        var strCon = 'blockContent='+$('#txtContent').val();
        $.post(makeUrl('addNote'),strCon,function(data,status){
          if(data.state==1){
            noteBook.addNote(data.content);
            loadTable();
            $('#txtContent').val('');
          }else{
            alert(data.content);
          }
        },'json');
      }
    }

    //4.0 校验数据是否有被修改
    function checkNoteData(){
      try {
        $.post(makeUrl('checkNoteData'),function(data,statue,xhr){
          if(data.state==1){
            alert('校验成功，数据未被篡改~！');
          }else{
            var serMsg = '';
            var resArr = data.content;
            $.each(resArr,function(i,e){
              serMsg = serMsg + e + '<br/>';
            });
            showMsg(serMsg);
          }
        });
      } catch (error) {
        console.log(error);
      }
    }
    
    // -------------------------- 三、节点处理----------------------------
    //5.0 启动节点服务
    function startWSServer(){
      try {
        var newPort = $('#txtAdr').val();
        $.post(makeUrl('startWSServer'),'nodePort='+newPort,function(data,statue,xhr){
          if(data.state==1){
            showMsg(data.content);
          }else{
            alert(data.content);
          }
        })
      } catch (error) {
        console.log(error);
      }
    }

    //6.0 加入节点网络
    function joinNodeNet(){
      try {
        //获取远程在网节点的 uri
        var nodeIp = $('#txtRemotNodeIP').val();
        var nodePort = $('#txtRemotNodePort').val();
        $.post(makeUrl('joinNodeNet'),'ip='+nodeIp+'&port='+nodePort,function(data,statue,xhr){
          if(data.state==1){
            showMsg(data.content);
          }else{
            alert(data.content);
          }
        })
      } catch (error) {
        console.log(error);
      }
    }

    // 显示最新节点列表
    function showNodeNet(){
      try {
        $.post(makeUrl('showNodeNet'),'just do it',function(data,statue,xhr){
          if(data.state==1){
            var uriArr = JSON.parse(data.content);
            $('#divNodeOpe').empty();
            $.each(uriArr,function(i,ele){
              $('#divNodeOpe').append('<span>'+ele+'</span>');
            })
          }else{
            alert(data.content);
          }
        })
      } catch (error) {
        console.log(error);
      }
    }

    // 同步区块链账本数据
    function reqBlockData(){
      try {
        $.post(makeUrl('reqBlockData'),'just do it',function(data,statue,xhr){
          if(data.state==1){
            showMsg('加载中.......');
            setTimeout(()=>{
              loadFromServer(loadTable);
              closeMsg();
            },1000);
            
          }else{
            alert(data.content);
          }
        })
      } catch (error) {
        console.log(error);
      }
    }
    // -------------------------- 四、dom处理----------------------------
    // 初始化
    $(function(){
      $('#divMsg').hide();

      $("#btnStartWSServer").click(startWSServer);
      $("#btnJoinNodeNet").click(joinNodeNet);
      $("#btnShowNodeNet").click(showNodeNet);
      


      $("#btnAddGen").click(addGenesis);
      $("#btnAddCon").click(addNote);
      $("#btnCheck").click(checkNoteData);
      $("#btnReqBlockData").click(reqBlockData);
      
      $("#close").click(closeMsg);
      loadFromServer(loadTable);
    })

    function loadTable(){
      if(noteBook.isEmpty()){
        $('#tbData').append('<tr><td colspan="6">暂无区块数据</td></tr>');
      }else{
        $('#tbData tr:gt(0)').empty();
        for (var i = 0; i < noteBook.list.length; i++) {
            //生成表格行，传入 捐款数据对象
            addTr(noteBook.getDataByIndex(i));
        }
      }
    }

    function addTr(dataObj) {
        //获取表格对象
        var tbList = gel("tbData");
        //追加一个新行（此时行已经在表格最后了）
        var rowNew = tbList.insertRow(-1);
        rowNew.setAttribute('dataId',dataObj.id);
        //为新行 添加列
        rowNew.insertCell(-1).innerHTML = dataObj.id;
        rowNew.insertCell(-1).innerHTML = dataObj.content;
        rowNew.insertCell(-1).innerHTML = timestampToTime(dataObj.timeStamp);
        
        var nounceC = rowNew.insertCell(-1);
        nounceC.style = 'font-size: 4px;';
        nounceC.innerHTML = dataObj.nounce;

        var hashC = rowNew.insertCell(-1);
        hashC.style = 'font-size: 4px;';
        hashC.innerHTML = dataObj.hash;

        var hashPre = rowNew.insertCell(-1);
        hashPre.style = 'font-size: 4px;';
        hashPre.innerHTML = dataObj.preHash;

        //rowNew.insertCell(-1).innerHTML = "<a href='javascript:void(0)' onclick='doDel(this)'>删</a> <a href='javascript:void(0)' onclick='edit(this)'>改</a>";//操作列
    }
  
  </script>
</head>

<body>
  <h1>区块链笔记本</h1>
  <div id="divMsg">
    <span id="content"></span>
    <span id="close">X 关闭</span>
  </div>

  <div>
    <input type="text" id="txtAdr" value="1011" placeholder="ip端口号" style="width: 300px;padding: 2px;">
    <input type="button" id="btnStartWSServer" value="启动节点服务" /><!--JoinNet-->
    目标节点：
    <input type="text" id="txtRemotNodeIP" placeholder="已知在网节点http地址" value="127.0.0.1" style="width: 100px;padding: 2px;">
    <input type="text" id="txtRemotNodePort" value="" placeholder="节点端口" style="width: 60px;padding: 2px;">
    <input type="button" id="btnJoinNodeNet" value="加入节点网络" />
    <input type="button" id="btnShowNodeNet" value="更新显示节点列表" />
    <input type="button" id="btnReqBlockData" value="请求同步区块数据" />
  </div>

  <fieldset id='divNodeOpe'>
    <legend>节点列表</legend>

  </fieldset>


  <div>
    <input type="text" id="txtContent" placeholder="请填写内容" style="width: 300px;padding: 2px;">
    <input type="button" id="btnAddGen" value="新增创世区块" />
    <input type="button" id="btnAddCon" value="新增普通区块" />
    <input type="button" id="btnCheck" value="数据校验" />
  </div>
  <table id="tbData">
    <tr>
      <th style="width:50px">编号</th>
      <th>内容</th>
      <th style="width:100px">创建日期</th>
      <th style="width:60px">NOC</th>
      <th style="width:230px">Hash</th>
      <th style="width:230px">PreHash</th>
    </tr>
  </table>
</body>

</html>
